package com.lk.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 使用org.code.jackson包去实现
 * 或者使用alibaba的JSON包 ：JSONObject.parseObject(json, Person.class);
 * @author lijun
 * @since 2018-05-03
 */
public class JsonStrToBeanUtils {
	
	private static Logger logger = LoggerFactory.getLogger(JsonStrToBeanUtils.class);	//日志记录
	public static final ObjectMapper mapper = new ObjectMapper();
	
	/**   
	* 获取泛型的Collection Type  
	* @param collectionClass 泛型的Collection   
	* @param elementClasses 元素类   
	* @return JavaType Java类型   
	* @since 1.0   
	*/   
	public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
	    return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
	}
	
	/**
	 * 把json字符串转换成List<javaBean>
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	public static <T> T strToListBean(String str, Class<T> cls) throws JsonParseException, JsonMappingException, IOException{
		JavaType javaType = getCollectionType(ArrayList.class, cls); 
	    T obj = mapper.readValue(str, javaType);
		return obj;
	}
	
	/**
	 * 把json字符串转换成List<javaBean>
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	public static <T> T strToBean(String str, Class<T> cls) throws JsonParseException, JsonMappingException, IOException{
		JavaType javaType = mapper.getTypeFactory().constructType(cls);
	    T obj = mapper.readValue(str, javaType);
		return obj;
	}
	
}
